package net.linxuehua.server.controller.admapi;/**
 * @author chenyan
 * @createTime 2021/1/11 14:27
 * @description description
 */

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.linxuehua.commons.core.R;
import net.linxuehua.server.dto.UserDTO;
import net.linxuehua.server.po.User;
import net.linxuehua.server.service.UserService;
import net.linxuehua.server.vaildate.UpdateValid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Slf4j
@Api(tags = {"用户接口"})
@RestController
@RequestMapping(value = "/admapi/user")
public class UserController {
    @Autowired
    private UserService userService;


    @ApiOperation(value = "获取用户个人信息")
    @GetMapping(value = "/{id}")
    public R getInfo(@PathVariable Integer id) {
        User user = userService.getById(id);
        return R.data(user);
    }


    //增加用户
    @ApiOperation(value = "新增用户")
    @PostMapping("/")
    public R add(@Validated @RequestBody UserDTO userDTO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("use_name", userDTO.getUserName());
        if (queryWrapper != null) {
            return R.error("用户名已被使用");
        }
        User user = userDTO.toUser();
        boolean temp = userService.save(user);
        return temp ? R.ok("添加成功") : R.error("添加失败");
    }

    //删除
    @ApiOperation(value = "删除用户")
    @DeleteMapping("/{id}")
    public R delete(@PathVariable Integer id) {
        boolean temp = userService.removeById(id);
        return temp ? R.ok("删除成功") : R.error("删除失败");
    }

    //修改
    @ApiOperation(value = "修改用户")
    @PutMapping(value = "/")
    public R update(@Validated(UpdateValid.class) @RequestBody UserDTO userDTO) {
        if (userDTO.getUserId() == null) {
            return R.error("修改失败，id不能为空");
        }
        User user = userDTO.toUser();
        User oldUser = userService.getById(userDTO.getUserId());
        if (user.getUserName() == null) {
            user.setUserName(oldUser.getUserName());
        }
        boolean temp = userService.updateById(user);
        return temp ? R.ok("修改成功") : R.error("修改失败");
    }
}
